package object;

/**
 * @TODO
 * @Author xu
 * 2025/3/10
 */class Address {
    String city;

    public Address(String city) {
        this.city = city;
    }
}

class Person implements Cloneable {
    String name;
    Address address;

    public Person(String name, Address address) {
        this.name = name;
        this.address = address;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person cloned = (Person) super.clone(); // 先执行浅拷贝
        cloned.address = new Address(this.address.city); // 深拷贝地址
        return cloned;
    }
}

public class DeepCopy {
    public static void main(String[] args) {
        Address address = new Address("New York");
        Person person1 = new Person("John", address);

        try {
            // 创建深拷贝
            Person person2 = (Person) person1.clone();

            // 修改原对象的地址
            person1.address.city = "Los Angeles";

            // 输出两个对象的信息
            System.out.println("Person 1: " + person1.name + ", City: " + person1.address.city);
            System.out.println("Person 2: " + person2.name + ", City: " + person2.address.city);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}
